const path = require('path')
const Koa = require('koa')
const Socket = require('koa-socket')
const static = require('koa-static')
const send = require('koa-send')

const socketIO = new Socket({
  ioOptions: {
    pingTimeout: 10000,
    pingInterval: 5000
  }
})

const app = new Koa()
const rooms = {}
const sockPool = {}

// 给应用注入socket
socketIO.attach(app)

app.use(static(
  path.join( __dirname,  './static/dist')
))

app.use(async (ctx, next) => {
  if (!/\./.test(ctx.request.url)) {
    await send(ctx, 'index.html', {
      root: path.join(__dirname, './'),
      maxage: 1000 * 60 * 60 * 24 * 7,
      gzip: true
    })
  } else {
    await next()
  }
})

app._io.on('connection', sock => {
  sock.on('join', data => {
    sock.join(data.roomId, () => {
        if (!rooms[data.roomId]) {
          rooms[data.roomId] = {}
        }

        const user = {
          id: sock.id,
          type: data.type
        }

        if (!rooms[data.roomId][data.type]) {
          rooms[data.roomId][data.type] = user
        }

        sockPool[`${data.roomId}-${data.type}`] = sock

        // 发给房间内所有人
        app._io.in(data.roomId).emit('joined', Object.values(rooms[data.roomId]))
    })
  })

  sock.on('candidate', data => {
    const target = sockPool[`${data.roomId}-${(data.type * 1 + 1) % 2}`]

    if (target) {
      target.emit('candidate', {
        candidate: data.candidate
      })
    }
  })

  sock.on('offer', data => {
    const target = sockPool[`${data.roomId}-${(data.type * 1 + 1) % 2}`]

    if (target) {
      target.emit('offer', {
        offer: data.offer
      })
    }
  })

  sock.on('answer', data => {
    const target = sockPool[`${data.roomId}-${(data.type * 1 + 1) % 2}`]

    if (target) {
      target.emit('answer', {
        answer: data.answer
      })
    }
  })

  sock.on('showQuestion', data => {
    const target = sockPool[`${data.roomId}-${(data.type * 1 + 1) % 2}`]

    if (target) {
      target.emit('showQuestion', {
        question: data.question,
        questionIndex: data.questionIndex
      })
    }
  })

  sock.on('code', data => {
    const target = sockPool[`${data.roomId}-${(data.type * 1 + 1) % 2}`]

    if (target) {
      target.emit('code', {
        code: data.code,
        index: data.index
      })
    }
  })
})

app._io.on('disconnect', sock => {
  console.info(sock.id + ' disconnect')
})

app.listen(3721, () => {
  console.log('app started at port 3721')
})
